import React, { Component } from 'react'
import { connect } from 'dva';
import moment from 'moment';
import { Table, message, Modal } from 'antd';
import Form from './components/SearchForm';
import { setDown } from './service';
import { checkInit } from '@/utils/util';

export interface Props {
  dispatch?: Function,
  children?: React.ReactNode,
  loading: boolean,
  list: {
    data: Array<any>,
    dataCnt: number
  },
  cond?: {
    pageSize: number
  };
  buttons?: Array<any>,
  dict?: object
}


let userIdList = [];

@connect(({ position_patrol_user, loading, menu }) => ({
  list: position_patrol_user.list || {},
  dict: position_patrol_user.dict || {},
  cond: position_patrol_user.cond || {},
  buttons: menu.buttons,
  loading: loading.effects['position_patrol_user/queryPage']
}))
class PositionPatrolUser extends Component<Props, any> {
  constructor(props) {
    super(props);
    this.initCurrent = this.initCurrent.bind(this);
  }
  state = {
    current: 1,
    selectedRowKeys: []
  };

  private queryData(offset = 1) {
    const { dispatch } = this.props;

    dispatch({
      type: 'position_patrol_user/queryPage',
      payload: {
        pageNum: offset
      },
    });
  }

  initCurrent() {
    this.setState({
      current: 1
    })
  }

  onSelectChange = (selectedRowKeys, rowData) => {
    userIdList = [];
    this.setState({
      selectedRowKeys
    });
    rowData.forEach(item => {
      userIdList.push(item.id);
    });
  }

  onShowSizeChange = (current, pageSize) => {
    const { dispatch, cond } = this.props;
    cond.pageSize = pageSize;
    dispatch({ type: `position_patrol_user/updateCond`, payload: cond }).then(() => {
      this.initCurrent()
    })
  }

  patrolSetDown = () => { // 批量移除巡逻人员
    Modal.confirm({
      title: '移除人员',
      content: '确认是否移除选中的巡检人员？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        if (userIdList.length > 0) {
          setDown({ userIdList }).then(() => {
            userIdList = [];
            this.setState({
              selectedRowKeys: []
            });
            this.queryData();
          })
        } else {
          message.warning('请选中操作对象', 1.5);
        }
      },
      onCancel() { }
    });
  };

  componentDidMount() {
    const { dispatch } = this.props;
    checkInit() ? dispatch({ type: `position_patrol_user/initCond` }) : this.queryData();
  }

  render() {
    const { buttons } = this.props;
    const btnList = {};
    buttons.forEach(item => {
      btnList[item.name] = item.name
    });

    const { data = [], dataCnt } = this.props.list;

    const ans = data && Array.isArray(data) ? data.map((item, index) => ({
      key: index,
      id: item.id,
      ind: index + 1 < 10 ? `0${index + 1}` : index + 1,
      realName: item.realName,
      mobile: item.mobile,
      createTime: item.createTime ? moment(item.createTime).format("YYYY-MM-DD hh:mm:ss") : '', // 报警时间
      jobNumber: item.jobNumber ? item.jobNumber : ' ',
      positionName: item.positionName,
      loginName: item.loginName ? item.loginName : ' ',
      email: item.email ? item.email : ' ',
      roleList: item.roleList && Array.isArray(item.roleList) ? (item.roleList.map(it => it.name)).join(' ') : ' ',
      groupList: item.groupList && Array.isArray(item.groupList) ? (item.groupList.map(it => it.name)).join(' ') : ' '
    })) : [];

    const pagination = {
      total: dataCnt,
      showTotal: (total: number) => `共 ${total} 条`,
      current: this.state.current,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      showSizeChanger: true,
      onChange: (current: number) => {
        this.setState({ current }, () => this.queryData(current));
      },
    };

    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: this.onSelectChange,
    };

    const columns = [{
      title: '工号',
      dataIndex: 'jobNumber',
    }, {
      title: '登录名',
      dataIndex: 'loginName',
    }, {
      title: '姓名',
      dataIndex: 'realName',
    }, {
      title: '职位',
      dataIndex: 'positionName',
    }, {
      title: '手机',
      dataIndex: 'mobile',
    }, {
      title: '电子邮箱',
      dataIndex: 'email',
    }, {
      title: '用户角色',
      dataIndex: 'roleList'
    }, {
      title: '部门',
      dataIndex: 'groupList',
    }];

    return (
      <div>
        <Form
          current={this.state.current}
          initCurrent={this.initCurrent}
          new={!!btnList['新增']}
          onChange={() => {
            this.patrolSetDown()
          }}
        />
        <Table
          columns={[{
            title: '序号',
            dataIndex: 'ind',
          }, ...columns]}
          pagination={pagination}
          dataSource={ans}
          bordered
          loading={this.props.loading}
          rowSelection={rowSelection}
        />
      </div>
    );
  }
}

export default PositionPatrolUser;
